<template>
    <div class="Screen_container">
        <div class="Screen_wrap " ref="main_screen">
            <!-- 批量导入组件 -->
            <component
                :is="item.componentName"
                v-on:Send="SendParams($event,item)"
                :ref="item.moduleId"
                v-for="(item,index) in componentsList"
                :key="item.id"
                :class="[item.componentName,item.moduleId]"></component>
        </div>
    </div>
</template>

<script>
    import store from '@/store'
    import {nanoid} from "nanoid";
   // import '@/utils/webScoketClient'
    export default {
        name: "ScreenHome",
        data() {
            return {
                vLine: [],
                hLine: [],
                // initScreenData: null,
                isWhich: '',
                componentsList: [],
                showSettings: true,
                props: null,
              ConnectionParams:{
                reqId: nanoid(8),
                operation: 1000,
                screenId: "screen_1",
              }
            };
        },
        methods: {
            // 接收子组件收到的参数发送给服务
            SendParams(val, a) {
                console.log(val, a, '发射');
                store.dispatch('SEND_PARAMS', val)
            },

          initWebSocket() {
            const wsuri = "ws://" + location.host + "/ws";
            this.$websocket = new WebSocket(wsuri);
            this.$websocket.onopen = this.websocketonopen;
            this.$websocket.onerror = this.websocketonerror;
            this.$websocket.onmessage = this.websocketonmessage;
            this.$websocket.onclose = this.websocketclose;
            this.$websocket.reconnection = true;
            this.$websocket.reconnectionAttempts = 5;
            this.$websocket.reconnectionDelay = 3000;
          },

          websocketonopen() {
            console.log("WebSocket连接成功");

            this.websocketsend(JSON.stringify(this.ConnectionParams));
          },

          websocketonerror(e) { //错误
            console.log("WebSocket连接发生错误");
          },

          //接收数据通过模块id去广播对应的数据，子组件订阅eventbus数据
          websocketonmessage(event) { //数据接收
            const Data = JSON.parse(event.data)
            switch (Number(Data.operation)) {
              case 1000:
                this.ConnectionParams.operation = 4000
                this.websocketsend(JSON.stringify(this.ConnectionParams));
                break;
              case 4000:
                store.commit("INIT_SCREEN", Data.data)
                break;
              case 4003:
                store.commit("UPDATA_SCREEN", Data.data)
                break;
              case 3001:
                store.commit("SELECT_MODULE", Data)
                console.log(Data, '选中模块');
                break;
              case 3002:
                console.log(Data, '取消选中模块');
                store.commit("CANCEL_MODULE", Data)
                break;
              case 3000:
                console.log(Data, '发送事件');
                store.commit("ISSUED_EVENT", Data)
                break;
              default:
                break;
            }
          },

          websocketsend(agentData) {//数据发送
            this.$websocket.send(agentData);
          },
          websocketclose(e) { //关闭
            console.log("WebSocket连接发生错误");
          },
        },
        computed: {
            //  ...mapState(['initScreenData','SelectModuleData']),
            INIT_SCREENDATA() {
                return this.$store.state.initScreenData;
            },
            // 选择模块
            selectModule() {
                return this.$store.state.SelectModuleData;
            },
            // 系统事件
            ISSUED_EVENT() {
                return this.$store.state.SystemEvent
            }
        },
        watch: {
            /**
             * 初始化屏幕
             */
            INIT_SCREENDATA(val) {
                this.initScreenData = []
                this.componentsList = []
                // console.log('数据变化', val, val.page);
                this.$refs.main_screen.style.width = val.screenWidth + 'px'
                this.$refs.main_screen.style.height = val.screenHeight + 'px'
                val.page.modules.forEach(element => {
                    this.componentsList.push(element)
                });
                // this.componentsList = val.page.modules
                setTimeout(() => {
                    this.componentsList.forEach(item => {
                        const el = document.getElementsByClassName(item.componentName)[0]
                        el.style.position = 'absolute'
                        el.style.width = item.attribute.width + 'px'
                        el.style.height = item.attribute.height + 'px'
                        el.style.top = item.attribute.top + 'px'
                        el.style.left = item.attribute.left + 'px'
                    })
                }, 200)
            },
            // 选择模块
            selectModule(val) {
                if (val.operation === 3001) {
                    this.$refs[val.moduleId][0].classList.add('newDiv');
                } else if (val.operation === 3002) {
                    this.$refs[val.moduleId][0].classList.remove('newDiv');
                }
            },
            // 系统动作事件
            // 事件向下传递
            ISSUED_EVENT(val) {
                console.log(val, '向下传递')
                val.data = JSON.parse(val.data)
                console.log(this.$refs[`${val.moduleId}`]);
                this.$refs[`${val.moduleId}`][0].receive(val)
            }
        },
      mounted() {
       this.initWebSocket()
        // 监听VueX事件变化并发送消息
        store.subscribeAction((mutation, state) => {
          if (mutation.type === "SEND_PARAMS") {
            this.$websocket.send(JSON.stringify(mutation.payload));
          }
        })
      }
    };
</script>

<style lang="scss" scoped>
    // .Screen_container {
    //     // .Screen_wrap {
    //     //     position: relative;
    //     //     margin: 0 auto
    //     // }
    // }
</style>